package com.cxh.util;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

/**
 * 字符串处理工具类
 * @author van.zheng
 *
 */
public class StringUtil extends StringUtils{

	/**
	 * 去除以逗号分隔的字符串的重复项
	 * @param str
	 * @return
	 */
	public static List<String> RemoveRepeatItem(String str) {
		if (!isNotBlank(str)) {
			return null;
		}
		List<String> list = new ArrayList<String>();
		String[] array = str.split(",");
		for (String s : array) {
			if (Collections.frequency(list, s) < 1) {
				list.add(s);
			}
		}
		return list;
	}

	/**
	 * 数字不足位数左补0
	 * @param str
	 * @param strLength
	 */
	public static String addZeroForNum(String str, int strLength) {
		int strLen = str.length();
		if (strLen < strLength) {
			while (strLen < strLength) {
				StringBuffer sb = new StringBuffer();
				sb.append("0").append(str); // 左补0
				str = sb.toString();
				strLen = str.length();
			}
		}
		return str;
	}

	public static String getRandomCode(){
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 10; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}
	
	/**
	  * 判断是否为数字（包含小数）正值 
	  * @param str 传入的字符串 
	  * @return 是整数返回true,否则返回false 
	*/

	  public static boolean isNumber(String str) {  
	        Pattern pattern = Pattern.compile("^[0-9]+([.]{1}[0-9]+){0,1}$");  
	        return pattern.matcher(str).matches();  
	  }

	/**
	 * 字符串+1方法，该方法将其结尾的整数+1,适用于任何以整数结尾的字符串,不限格式，不限分隔符。
	 * @author zxcvbnmzb
	 * @param testStr 要+1的字符串
	 * @return +1后的字符串
	 * @exception NumberFormatException
	 */
	public static String addOne(String testStr){
		String[] strs = testStr.split("[^0-9]");//根据不是数字的字符拆分字符串
		String numStr = strs[strs.length-1];//取出最后一组数字
		if(numStr != null && numStr.length()>0){//如果最后一组没有数字(也就是不以数字结尾)，抛NumberFormatException异常
			int n = numStr.length();//取出字符串的长度
			int num = Integer.parseInt(numStr)+1;//将该数字加一
			String added = String.valueOf(num);
			n = Math.min(n, added.length());
			//拼接字符串
			return testStr.subSequence(0, testStr.length()-n)+added;
		}else{
			throw new NumberFormatException();
		}
	}

}
